<template class="uploadDom">
  <div 
>
    <!-- action="http://47.97.79.225:9020/fileMgr/v1/oss/upload/aliyun" -->
    <el-upload action='' :class="hiddenUp?'img-hide':''" :http-request="requestHttp" list-type="picture-card"
      :on-success="successHandle" :on-exceed="outInputFile" :file-list="updataArr" :limit="limit"
      :before-upload="beforeUploadHandle" v-loading.fullscreen.lock="fullscreenLoading">
      <!-- <i class="el-icon-plus"></i> -->
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>

          <span v-if="disable" class="el-upload-list__item-delete" @click="handleRemove(file,updataArr)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>

      <div class="el-upload__tip" slot="tip" v-if="tip">{{tip}}</div>

    </el-upload>

    <el-dialog :visible.sync="dialogVisible2" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    props: {
      value: {
        type: Array,
        default: []
      },

      limit: {
        type: Number,
        default: 6
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      clearVisible: {
        type: Boolean,
        default: false
      },
      tip: {
        type: String,
        default: null
      },
      disable: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        loading: false,
        visible: false,
        url: '',
        num: 0,
        successNum: 0,
        updataArr: [], // 回显值
        urlUidImg: [], // 上传值
        hiddenUp: false,
        removeType: false,
        dialogImageUrl: '',
        dialogVisible2: false,
        fullscreenLoading: false
      }
    },
    watch: {
      dialogVisible (n, o) {
        if (!n) {
          this.updataArr = []
        }
      },

      value (n, o) {
        console.log('jianting')
  
        this.updataArr = []
        if (n.length > 0) {
          n.forEach(item => {
            let obj = new Object()
            obj.url = item
            this.updataArr.push(obj)
          })
        }
        let that = this
        setTimeout(() => {
          this.loading = false
        }, 1000)

        this.length()
      }
    },
    mounted () {
      console.log(this.value, 111)
      if (this.value) {
        this.value.forEach(item => {
          let obj = new Object()
          obj.url = item
          this.updataArr.push(obj)
        })
        this.length()
      }
    },
    methods: {
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible2 = true
      },
      handleRemove (file, fileList) {
        let newArr = []
        this.updataArr.forEach(e => {
          if (e.url !== file.url) {
            newArr.push(e.url)
          }
        })
        this.length()
        this.$emit('updataImg', newArr)
      },

      // 上传之前
      beforeUploadHandle (file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG /png格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return (isJPG || isPNG) && isLt2M
        this.num++
        this.loading = true
      },
      // 随机生成文件名
      random_string (len) {
        len = len || 32
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
        var maxPos = chars.length
        var pwd = ''
        for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos))
        }
        return pwd
      },
      requestHttp (file) {
        this.loading = true
        let res, ossData, dir
        this.fullscreenLoading = true
        axios.get(this.$config.upload_url).then(keys => {
          this.fullscreenLoading = false
          if (keys.data.code == 200) {
            res = JSON.parse(keys.data.data)
            ossData = new FormData()
            let imgname = this.random_string(8) + '.' + file.file.name.split('.').pop()
            dir = 'img/admin/' + imgname
            this.topUrl = res.host + '/' + 'img'

            ossData.append('name', imgname)
            ossData.append('key', dir)
            ossData.append('policy', res.policy)
            ossData.append('OSSAccessKeyId', res.accessid)
            ossData.append('success_action_status', 200)
            ossData.append('signature', res.signature)
            ossData.append('file', file.file, imgname)
          }
        }).then(() => {
          axios.post(res.host, ossData).then(obj => {
            if (obj.status == 200) {
              let editorArr = []
              this.urlUidImg = this.updataArr
              this.urlUidImg.push({
                url: res.host + '/' + dir,
                uid: file.file.uid
              })
              this.urlUidImg.forEach(element => {
                if (element.url) {
                  editorArr.push(element.url)
                } else {
                  editorArr.push(element)
                }
              })
              this.$emit('updataImg', editorArr)
              this.length()
            }
          })
        })
      },
      outInputFile (files, fileList) {
        if (fileList.length >= this.limit) {
          this.hiddenUp = true
          this.$message.warning('最多只能上传' + this.limit + '张图片')
          return false
        } else {
          this.hiddenUp = false
        }
      },
      length () {
        if (this.updataArr.length >= this.limit) {
          this.hiddenUp = true
        } else {
          this.hiddenUp = false
        }
      },
      // 上传成功
      successHandle (response, file, fileList) {
        this.successNum++
      }

    }
  }
</script>
<style lang="scss" scoped>
  .img-hide .el-upload--picture-card {
    display: none;
  }

  .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    height: 146px !important;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    line-height: 148px !important;
  }
</style>
<style>
/* .el-loading-spinner .path{
      stroke: #c8291c;
    } */
</style>
